package kr.co.boogui.service;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import kr.co.boogui.dao.CinemaDAO;
import kr.co.boogui.dao.MemberDAO;
import kr.co.boogui.dao.MovieDAO;
import kr.co.boogui.dao.NewsDAO;
import kr.co.boogui.dao.ReservationDAO;
import kr.co.boogui.dao.SalesDAO;
import kr.co.boogui.dao.ShowingDAO;
import kr.co.boogui.model.CinemaVO;
import kr.co.boogui.model.MemberVO;
import kr.co.boogui.model.MovieVO;
import kr.co.boogui.model.NewsVO;
import kr.co.boogui.model.ParamVO;
import kr.co.boogui.model.ShowingVO;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

public class AdminService {
	public static String adminChk(HttpServletRequest req, String page) {
		HttpSession sess = req.getSession();
		String viewPage = "f|/WEB-INF/jsp/admin/admin.jsp";
		try {
			if (sess.getAttribute("uid").equals("admin")) {
				req.setAttribute("action", page + ".jsp");
			} else {
				viewPage = "r|index.bi";
			}
		} catch (NullPointerException ne) {
			viewPage = "r|index.bi";
		}
		
		return viewPage;
	}	// adminChk
	
	public static boolean cinemaRegistry(HttpServletRequest req) throws IOException {
		boolean result = false;
		CinemaVO c = new CinemaVO();
		req.setCharacterEncoding("UTF-8");
		int theater = Integer.parseInt(req.getParameter("theater"));
		for (int i = 1; i<=theater; ++i){
			String zipcode = req.getParameter("zip1")+"-"+req.getParameter("zip2");
			System.out.println(req.getParameter("zip1"));
			System.out.println(req.getParameter("addr2"));
			System.out.println(zipcode);
			String zipseq = CinemaDAO.readZipseq(zipcode);
			c.setZipseq(zipseq);
			c.setCineaddr(req.getParameter("addr2"));
			c.setCinename(req.getParameter("cinename"));
			c.setTheater(i+"관");
			if (CinemaDAO.insertCinema(c)) result = true;
		}		
		
		return result;
	}	// cinemaRegistry
	
	// 영화 등록 (form 값 입력)
	public static boolean movieFrmRegistry(MultipartRequest mreq) throws ServletException, IOException {
		boolean result = false;
		MovieVO mov = new MovieVO();	
		mov.setTitle(mreq.getParameter("title"));
		mov.setGenre1(mreq.getParameter("genre1"));
		mov.setGenre2(mreq.getParameter("genre2"));
		mov.setGenre3(mreq.getParameter("genre3"));
		mov.setDirector(mreq.getParameter("director"));
		mov.setActor1(mreq.getParameter("actor1"));
		mov.setActor2(mreq.getParameter("actor2"));
		mov.setActor3(mreq.getParameter("actor3"));
		mov.setRate(mreq.getParameter("rate"));
		mov.setRunningtime(mreq.getParameter("runningtime"));
		mov.setPlaydate(mreq.getParameter("playdate"));
		mov.setSynop(mreq.getParameter("synop"));	
		
		if(MovieDAO.insertMovie(mov)){
			result = true;
		} else {
			result = false;
		}
		return result;
	}	// movieFrmRegistry
	
	// 파일명
	public static String renameFile() {
		return MovieDAO.readMovno();
	}	// renameFile
	
	// 영화 등록 (파일, 정보)
	public static boolean movieRegistry(HttpServletRequest req) {
		boolean result = false;

	//	String fpath = "d:/CDN/boogui/poster/";
		String fpath = "/home/hosting_users/jiinn/CDN/boogui/poster/";
		int size = 1024 * 1024 * 5;
		try {
			MultipartRequest mreq = new MultipartRequest(req, fpath, size, "UTF-8", new DefaultFileRenamePolicy());
			Enumeration formNames = mreq.getFileNames(); // 폼의 이름 반환
			String formName = (String) formNames.nextElement(); // 자료가 많을 경우엔
																// while 문을 사용
			String fileName = mreq.getFilesystemName(formName); // 파일의 이름 얻기
			if (fileName == null) { // 파일이 업로드 되지 않았을때
				System.out.println("fail");
			} else { // 파일이 업로드 되었을때
				if (movieFrmRegistry(mreq)) {
					result = true;
					String fname = renameFile();
					File oldFile = new File(fpath + fileName);
					File file = new File(fpath + fname + ".jpg");
					oldFile.renameTo(file);
					resizeS(fpath, fname, 195);
				}
			} // end if
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	} // movieRegistry

	// 포스터 임시저장
	public static String tmpPoster(HttpServletRequest req) {
		String result = "";
		String fpath = "/home/hosting_users/jiinn/CDN/boogui/temp/";
//		String fpath = "d:/CDN/boogui/temp/";
		int size = 1024 * 1024 * 5;
		try {
			MultipartRequest mreq = new MultipartRequest(req, fpath, size, "UTF-8", new DefaultFileRenamePolicy());
			Enumeration formNames = mreq.getFileNames();
			String formName = (String) formNames.nextElement();
			String fileName = mreq.getFilesystemName(formName);
			if (fileName == null) {
				System.out.println("fail");
			} else {
				result = fileName;
			} // end if
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	} // tmpPoster

	// 뉴스 등록 (form 값 입력)
	public static boolean newsFrmRegistry(MultipartRequest mreq)
			throws ServletException, IOException {
		boolean result = false;
		NewsVO nov = new NewsVO();
		nov.setNewstit(mreq.getParameter("newstit"));
		nov.setNewscontents(mreq.getParameter("newscontents"));
		nov.setNewstype(Integer.parseInt(mreq.getParameter("newstype")));
		nov.setWriter(mreq.getParameter("writer"));
		if (NewsDAO.writeNews(nov)) {
			result = true;
		} else {
			result = false;
		}
		return result;
	}

	// 파일명
	public static String renameNFile() {
		return NewsDAO.readNewsno();
	}

	// 뉴스 등록 (파일, 정보)
	public static boolean newsRegistry(HttpServletRequest req) throws Exception {
		boolean result = false;

	//	String fpath = "d:/CDN/boogui/news/";
		String fpath = "/home/hosting_users/jiinn/CDN/boogui/news/";
		int size = 1024 * 1024 * 5;
		try {
			MultipartRequest mreq = new MultipartRequest(req, fpath, size,
					"UTF-8", new DefaultFileRenamePolicy());
			Enumeration formNames = mreq.getFileNames(); // 폼의 이름 반환
			String formName = (String) formNames.nextElement(); // 자료가 많을 경우엔
																// while 문을 사용
			String fileName = mreq.getFilesystemName(formName); // 파일의 이름 얻기
			if (fileName == null) { // 파일이 업로드 되지 않았을때
				System.out.println("fail");
			} else { // 파일이 업로드 되었을때
				if (newsFrmRegistry(mreq)) {
					result = true;
					String fname = renameNFile();
					File oldFile = new File(fpath + fileName);
					File file = new File(fpath + fname + ".jpg");
					oldFile.renameTo(file);
					resizeS(fpath, fname, 310);
				}
			} // end if
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}
	
	/* 이미지 리사이징 */
	public static void resizeS(String fpath, String fname, int width) {
		String imgReadFile = fpath + fname + ".jpg";
		String imgWriteFile = fpath + "small/" + fname + ".jpg";

		try {
			FileInputStream fis = new FileInputStream(imgReadFile);
			byte[] data = new byte[fis.available()];

			fis.read(data);
			fis.close();
			Image image = Toolkit.getDefaultToolkit().createImage(data);

			File file = new File(imgReadFile);
			BufferedImage in_bi = ImageIO.read(file);
			int h = in_bi.getHeight();
			int w = in_bi.getWidth();
			int n_h = (h * width) / w;

			Image rtnImage = image.getScaledInstance(width, n_h,
					Image.SCALE_SMOOTH);

			MediaTracker tracker = new MediaTracker(new java.awt.Frame());
			tracker.addImage(rtnImage, 0);
			tracker.waitForAll();

			BufferedImage bi = new BufferedImage(rtnImage.getWidth(null),
					rtnImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
			Graphics g = bi.getGraphics();
			g.drawImage(rtnImage, 0, 0, null);
			g.dispose();
			ByteArrayOutputStream bas = new ByteArrayOutputStream();
			ImageIO.write(bi, "jpeg", bas);
			byte[] writeData = bas.toByteArray();

			DataOutputStream dos = new DataOutputStream(
					new BufferedOutputStream(new FileOutputStream(imgWriteFile)));
			dos.write(writeData);
			dos.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	} // resizeS
	// 상영정보 등록
	public static boolean showingRegistry(HttpServletRequest req) throws IOException {
			boolean result = false;
			ShowingVO s = new ShowingVO();
			req.setCharacterEncoding("UTF-8");		
			
			String hinfos[] = req.getParameterValues("hinfo");
			for (int i=0; i<hinfos.length; ++i){
				String infos[] = hinfos[i].split("/");
				s.setMovno(infos[0]);
				s.setCno(infos[1]);
				s.setShdate(infos[2]);
				s.setShtime(infos[3]);
				if (ShowingDAO.insertShowing(s)) result = true;
			}
					
			return result;
		}	// showingRegistry

	// 신규 가입 회원
	public static void readNewMember(HttpServletRequest req) {
		req.setAttribute("member", MemberDAO.selectNewMember());
	}
	
	// 메인 화면 영화
	public static void readMainMovie(HttpServletRequest req) {
		req.setAttribute("movie", MovieDAO.selectMainMovie("reservationrate"));
	}
	
	// 오늘 가입 회원
	public static void readTodayRegiMember(HttpServletRequest req) {
		req.setAttribute("memBadge", MemberDAO.selectTodayRegiMember());
	}

	// 회원 정보 조회
	public static void readMemberList(HttpServletRequest req) {
		System.out.println("ftype : " + req.getParameter("ftype"));
		System.out.println("fkye : " + req.getParameter("fkey"));
		int orderNum = 0;
		int cpage = 1, perpage = 15, startno = 0;
		int allpage, startnav = 1, startmno;
		String ftype = "", fkey = "";
		String order = "rdate";
		if (req.getParameter("orderNum")!=null) {
			orderNum = Integer.parseInt(req.getParameter("orderNum"));
		}	// end if
		switch (orderNum) {
		case 1: order = "mno"; break;
		case 2: order = "uid"; break;
		case 3: order = "uname"; break;
		case 4: order = "phone"; break;
		case 5: order = "email"; break;
		case 6: order = "addr"; break;
		case 7: order = "genre"; break;
		default: order = "rdate"; break;
		}	// end switch
		
		if (req.getParameter("ftype")!=null) {
			ftype = req.getParameter("ftype");
		}
		if (req.getParameter("fkey")!=null) {
			fkey = req.getParameter("fkey");
		}
		if (req.getParameter("cpage")!=null) {
			cpage = Integer.parseInt(req.getParameter("cpage"));
			startno = (cpage-1)*perpage;
		}
		int total = readTotalMember(req);
		allpage = (int)Math.ceil((total/(float)perpage));
		startnav = ((cpage-1)/10)*10 + 1;
		startmno = total - (perpage*(cpage-1));
		
		req.setAttribute("cpage", cpage);
		req.setAttribute("ftype", ftype);
		req.setAttribute("fkey", fkey);
		req.setAttribute("perpage", perpage);
		req.setAttribute("startno", startno);
		
		req.setAttribute("total", total);
		req.setAttribute("allpage", allpage);		
		req.setAttribute("startnav", startnav);		
		req.setAttribute("startbno", startmno);
		
		req.setAttribute("member_list", MemberDAO.selectMemberList(order, startno, ftype, fkey));
	}
	
	// 회원 총 수
	public static void readAllTotalMember(HttpServletRequest req) {		
		req.setAttribute("total_member", MemberDAO.selectAllTotalMember());
	}

	// 검색 조건에 맞는 회원 총 수
	public static int readTotalMember(HttpServletRequest req) {
		int result = 0;
		String ftype = req.getParameter("ftype");
		String fkey = req.getParameter("fkey");
		result = MemberDAO.selectTotalMember(ftype, fkey);
		return result;
		
	}

	// 관리자 페이지 회원 정보 수정
	public static void modifyAdmMember(HttpServletRequest req) {		
		MemberVO m = new MemberVO();
		m.setMno(req.getParameter("mno"));
		m.setPhone(req.getParameter("phone"));
		m.setEmail(req.getParameter("email"));
		m.setAddr(req.getParameter("addr"));
		if (MemberDAO.updateAdmMember(m)) {
			req.setAttribute("result", "success");
		} else {
			req.setAttribute("result", "fail");
		}
	}
	
	// 관리자 페이지 회원 정보 수정에 회원 정보 뿌리기
	public static void readAdmMember(HttpServletRequest req) {
		MemberVO m = new MemberVO();
		m.setMno(req.getParameter("mno"));
		req.setAttribute("member", MemberDAO.selectAdmMember(m));
	}
	
	// 회원 삭제
	public static void removeMember(HttpServletRequest req) {
		MemberVO m = new MemberVO();
		m.setMno(req.getParameter("mno"));
		if (MemberDAO.deleteMember(m)) {
			req.setAttribute("result", "success");
		} else {
			req.setAttribute("result", "fail");
		}
		
	}
	
	public static void removeNews(HttpServletRequest req){
		NewsVO n = new NewsVO();
		n.setNewsno(req.getParameter("newsno"));
		if(NewsDAO.deleteNews(n)){
			req.setAttribute("result", "success");
		}else{
			req.setAttribute("result", "false");
		}		
	}
	
	public static void readPayStay(HttpServletRequest req) {
		req.setAttribute("payStay", ReservationDAO.selectIspay());
		req.setAttribute("payCnt", ReservationDAO.selectPayCnt());
	}
	
	public static void readSales(HttpServletRequest req) {
		req.setAttribute("sales", SalesDAO.selectSales());
		
	}
	
}
